package com.dayatang.android.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.dayatang.android.config.Config;

public class HttpUtil {
	
	public static String host = android.net.Proxy.getDefaultHost();
	public static int port = android.net.Proxy.getDefaultPort();
	
	private static HttpURLConnection httpURLConnection = null;
	
	// 检查网络是否需要代理
	public static boolean CheckNetworkProxy(Context context) {
		NetworkInfo networkInfo = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
		if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
			if (host != null && port != -1) {
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	
	// 返回代理类
	public static java.net.Proxy getProxy(URL url) {
		InetSocketAddress inetAddress = new InetSocketAddress(host, port);  
		java.net.Proxy.Type proxyType = java.net.Proxy.Type.valueOf(url.getProtocol().toUpperCase());  
		java.net.Proxy javaProxy = new java.net.Proxy(proxyType, inetAddress); 
		return javaProxy;
	}
	
	
	// 返回InputStream,主要用于下载文件
	public static InputStream getInputStream(String urlAddress,Context context){
		try {
			URL url = new URL(urlAddress);
			if (CheckNetworkProxy(context)) {
				httpURLConnection = (HttpURLConnection) url.openConnection(getProxy(url));
				httpURLConnection.connect();
				return httpURLConnection.getInputStream();
			}else{
				return getNoProxyInputStream(urlAddress);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			CloseInputOrHttp(null,httpURLConnection);
		}
		return null;
	}
	
	// 关闭输入流,httpConn
	private static void CloseInputOrHttp(InputStream is,HttpURLConnection httpConn){
		try {  
			if (is != null) {  
			    is.close();  
			}  
			if (httpConn != null) {  
			   httpConn.disconnect();  
			}  
		} catch (IOException ie) {  
			ie.printStackTrace();  
		}
	}
	
	// 返回不用代理连接的输入流
	private static InputStream getNoProxyInputStream(String urlAddress){
	    HttpClient client = new DefaultHttpClient();    
	    try {    
	    	HttpPost request = new HttpPost(new URI(urlAddress));
	        HttpResponse response = client.execute(request);    
	        if (response.getStatusLine().getStatusCode() == 200) { 
	             HttpEntity entity = response.getEntity();    
	             return entity.getContent();
	        }
	    } catch (URISyntaxException e) {    
	         e.printStackTrace();
	    } catch (ClientProtocolException e) {    
	         e.printStackTrace();
	    } catch (IOException e) {    
	         e.printStackTrace();
	    }
		return null;    
	}
	
	// 将inputStream转化为String
	public static String InputStreamToString(InputStream inputStream) {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			StringBuilder sb = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			CloseInputOrHttp(inputStream,null);
		}
		return null;
	}
	
	// 处理url请求
	public static String httpclient(String urlAddress,Context context) {    
		try {
			URL url = new URL(urlAddress);
			if (CheckNetworkProxy(context)) {
				httpURLConnection = (HttpURLConnection) url.openConnection(getProxy(url));
				httpURLConnection.connect();
				return InputStreamToString(httpURLConnection.getInputStream());
			} else {
				return NoProxyUrl(urlAddress);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			CloseInputOrHttp(null, httpURLConnection);
		}
		return null;
    }  
	
	// 不代理网络处理url
	private static String NoProxyUrl(String urlAddress) {
		return getDataByParam(urlAddress,null);
	}

	// 基站定位要处理的数据
	public static String getJsonBySIM(String urlAddress, String query, Context context) {    
		try {
			URL url = new URL(urlAddress);
			if (CheckNetworkProxy(context)) {
				httpURLConnection = setURLConnectionProperties(url,getProxy(url));
				ObjectOutputStream objOutputStrm = getObjOutStream(httpURLConnection);
				objOutputStrm.writeObject(query);
				objOutputStrm.flush();
				
				return InputStreamToString(httpURLConnection.getInputStream());
			}else{
				return getDataByParam(urlAddress,query);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			CloseInputOrHttp(null, httpURLConnection);
		}
		return null;
    }  

	// 设置httpURLConnection属性
	private static HttpURLConnection setURLConnectionProperties(URL url,java.net.Proxy proxy) throws IOException, ProtocolException {
		HttpURLConnection httpUrlConnection;

		httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
		httpUrlConnection.setDoOutput(true);
		httpUrlConnection.setDoInput(true);
		httpUrlConnection.setUseCaches(false);
		httpUrlConnection.setRequestProperty("Content-type", "application/json");
		httpUrlConnection.setRequestMethod("POST");

		try {
			httpUrlConnection.connect();
			httpUrlConnection.setConnectTimeout(1);
			httpUrlConnection.setReadTimeout(1);
		} catch (ConnectException e1) {
			e1.toString();
		}
		return httpUrlConnection;
	}
	
	
	// 得到对象输出流
	private static ObjectOutputStream getObjOutStream(HttpURLConnection httpUrlConnection) throws IOException {
		OutputStream outStrm;// 得到HttpURLConnection的输出流
		ObjectOutputStream objOutputStrm;// 对象输出流
		// 此处getOutputStream会隐含的进行connect(即：如同调用上面的connect()方法，
		// 所以在开发中不调用上述的connect()也可以)。
		outStrm = httpUrlConnection.getOutputStream();
		
		// 现在通过输出流对象构建对象输出流对象，以实现输出可序列化的对象。
		// 使用JSON传值
		objOutputStrm = new ObjectOutputStream(outStrm);
		return objOutputStrm;
	}

	private static String getDataByParam(String urlAddress, String query) {
		HttpClient client = new DefaultHttpClient();
		try {
			HttpPost request = new HttpPost(new URI(urlAddress));
			if(query != null) {
	            StringEntity sentity = new StringEntity(query);
	            request.setEntity(sentity);
			}
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				return EntityUtils.toString(entity, Config.UTF);
			} else if (response.getStatusLine().getStatusCode() == 500) {
				return Config.SERVERDIE;
			} else {
				return Config.ERROR;
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return e.toString();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return e.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return e.toString();
		}
	}
}
